package handlers

import (
	"ai/internal/aiserver/request"
	"ai/internal/response"
	"ai/internal/service"
	"net/http"

	"github.com/gin-gonic/gin"
)

// @Summary Login
// @Description Login with username and password
// @Tags auth
// @Accept json
// @Produce json
// @Param loginRequest body request.ReqLogin true "Login request"
// @Success 200 {object} response.Response{data=string} "Login successful"
// @Failure 400 {object} response.Response "Invalid request"
// @Failure 401 {object} response.Response "Invalid username or password"
// @Router /login [post]
func LoginHandler(c *gin.Context, services *service.ServiceManager) {
	var request request.ReqLogin
	if err := c.ShouldBindJSON(&request); err != nil {
		response.Error(c, http.StatusBadRequest, "Invalid request")
		return
	}

	// Authenticate user
	user, err := services.UserService.Authenticate(request.Username, request.Password)
	if err != nil {
		response.Error(c, http.StatusUnauthorized, "Invalid username or password")
		return
	}

	// Generate token
	token, err := services.UserService.GenerateToken(user)
	if err != nil {
		response.Error(c, http.StatusInternalServerError, "Failed to generate token")
		return
	}

	response.Success(c, gin.H{"message": "Login successful", "token": token})
}
